<?php
/**
 * Created by PhpStorm.
 * User: zhaoq02
 * Date: 2016-04-08
 * Time: 14:04
 */

namespace business\base\services;


use business\base\models\BasicCategoryModel;
use Exception;
use Yii;

class BasicCategoryService {

    const STATUS_LIVENESS = 1;
    const  CACHE_TIME_OUT = 600;

    /**
     * @param $categoryCode
     * @return null | BasicCategoryModel
     */
    public function  getCategoryByCode($categoryCode)
    {
        $BasicCategoryList = self::getBasicCategoryCache(true);
        if (empty($BasicCategoryList)) {
            return null;
        }
        if (array_key_exists($categoryCode, $BasicCategoryList)) {
            return $BasicCategoryList[$categoryCode];
        } else {
            return null;
        }
    }

    /***
     * @param $categoryName
     * @return null|string
     */
    public function getCategoryCodeByName($categoryName){
        $BasicCategoryList = self::getBasicCategoryList();
        if (empty($BasicCategoryList)) {
            return null;
        }
        foreach ($BasicCategoryList as $BasicCategory) {
            if(!empty($BasicCategory)){
                if ($BasicCategory->categoryStatus == self::STATUS_LIVENESS && $BasicCategory->categoryName == $categoryName) {
                    return $BasicCategory->categoryCode;
                }
            }
        }
        return null;
    }

    /**
     * @param $isAllBasicCategoryNode
     * @return array
     */
    public function getBasicCategoryCache($isAllBasicCategoryNode)
    {
        $liveBasicCategory = [];
        $allBasicCategory = [];
        $BasicCategoryList = self::getBasicCategoryList();
        if (empty($BasicCategoryList)) {
            return [];
        }
        foreach ($BasicCategoryList as $BasicCategory) {
            if(!empty($BasicCategory)){
                if ($BasicCategory->categoryStatus == self::STATUS_LIVENESS) {
                    $liveBasicCategory[$BasicCategory->categoryCode] = $BasicCategory;
                }
                $allBasicCategory[$BasicCategory->categoryCode] = $BasicCategory;
            }
        }
        if ($isAllBasicCategoryNode) {
            return $allBasicCategory;
        } else {
            return $liveBasicCategory;
        }
    }

    /**
     * @return array|BasicCategoryModel[]
     *
     */
    public function  getBasicCategoryList()
    {
        try {
            if (empty($result)) {
                $result = BasicCategoryModel::find()->orderBy("parent_code, display_order")->all();
            }
            return $result;
        } catch (Exception $ex) {
            yii::info("加载缓存异常[BasicCategoryService.GetBasicCategoryList]" . $ex);
            return new BasicCategoryModel();
        }
    }

    public function getCategoryNameByCode($categoryCode)
    {
        if(empty($categoryCode))
            return "";
        $data=BasicCategoryModel::findOne(['category_code'=>$categoryCode]);
        return !empty($data) ? $data->category_name:"";
    }

    /*
   *  根据分类code，获取对应名称
   *  $categories,分类编码：code1,code2,code3
   * */
    public function  getCategoryNameByCodes($categories,$split="；")
    {
        if (empty($categories)) {
            return null;
        }
        $categoriesStr = "'" . str_replace(",", "','", $categories) . "'";
        $sql = "SELECT GROUP_CONCAT(category_name SEPARATOR :split) from b2b_parameter.bsp_basic_forest where category_code in (" . $categoriesStr . ")";
        $command = Yii::$app->db->createCommand($sql,[':split'=>strval($split)]);
        $categoryNames = $command->queryScalar();
        return $categoryNames;
    }

    public  function  getFirstCategorys()
    {
        $result = self::getChildCategorys("0");
        return $result;
    }

    public  function  getChildCategorys($parentCode)
    {
        if($parentCode!=null) {
            $sql = "     SELECT    category_id as cid,
                                           category_name  as cname,
                                           category_code as category_code
                        FROM    b2b_parameter.bsp_basic_forest
                     WHERE parent_code=:parentCode  and category_status=1 and category_name<>'其他'
                                                                       order by display_order
                                    ";
            $connection = Yii::$app->db;
            return $connection->createCommand($sql, [':parentCode' => $parentCode])->queryAll();
        }
        else
        {
            return [];
        }
    }


    /**
     * 获取常用分类
     */
    public  function  getCommonForest($limit=20)
    {
        $sql = "
                SELECT a.category_code as cid,
                        a.category_code ,
                        a.category_name as cname,
                        a.top_code
                FROM b2b_parameter.bsp_common_forest a
               ORDER BY display_order asc   limit :limit
                                    ";
        $connection = Yii::$app->db;
        return $connection->createCommand($sql, [ ':limit' => $limit ])->queryAll();
    }

    public  function  getChildCategorysByKeyWord($keyWord)
    {
        if(!empty($keyWord)) {
            $sql = "select c.category_id cid,c.category_name cname,c.category_code,
                                          ifnull(c.category_code,'') as basic_forest_code,
                                          ifnull(c.category_name,'') as  basic_forest_name,
                                          a.category_code as top_code,
                                           a.category_name as top_name
                    FROM b2b_parameter.bsp_basic_forest a
                    INNER JOIN b2b_parameter.bsp_basic_forest b on b.parent_code=a.category_code
                    INNER JOIN b2b_parameter.bsp_basic_forest c on c.parent_code=b.category_code
                    where a.parent_code='0' and c.category_name like concat('%',:keyWord,'%') and c.category_name<>'其他'
                    order by c.display_order";
            $connection = Yii::$app->db;
            return $connection->createCommand($sql, [':keyWord' => $keyWord])->queryAll();
        }
        else
        {
            return [];
        }
    }


    public function  getChildCategorysName($categoryCode, $limit = 3)
    {
        if (empty($categoryCode)) {
            return "";
        }
        $sql = <<<SQL
                          SELECT REPLACE(GROUP_CONCAT(category_name),',','/') as categoryName
                                    from
                                    (
                                    select c.category_name
                                    FROM b2b_parameter.bsp_show_forest a
                                    INNER JOIN b2b_parameter.bsp_show_forest b on b.parent_code=a.category_code
                                    INNER JOIN b2b_parameter.bsp_show_forest c on c.parent_code=b.category_code
                                    where a.category_code=:categoryCode
                                    order by c.display_order
                                    limit :limit
                                    ) t
SQL;
        return \Yii::$app->getDb()->createCommand($sql, [':categoryCode'=>$categoryCode,':limit' => $limit])->queryScalar();

    }

    /**
     * @param string $codes 以逗号分隔的code字符串 如：code1,code2,code3
     * @param string $glue 名称的连接符 如：","
     * @return string 返回对象的名称字符串
     */
    public  function getCategoryNamesByCodeStrs($codes, $glue=","){
        if(empty($codes))
            return "";
        $categoryNameList = [];
        $serviceCategoryList = explode($glue, $codes);
        foreach($serviceCategoryList as $categoryCode){
            $category = $this->getCategoryByCode($categoryCode);
            if(!empty($category)){
                array_push($categoryNameList, $category->categoryName);
            }
        }
        return implode($glue, $categoryNameList);
    }
    public function getCategoryNamesByCodesFromDb($codes, $glue=",")
    {
        $categoryNameList = BasicCategoryModel::find()->select('category_name')->where(['in', 'category_code', explode(',', $codes)])
            ->andWhere('category_status=1')->asArray()->all();
        if(!empty($categoryNameList)){
            return implode($glue, array_column($categoryNameList, 'category_name'));
        }else{
            return '';
        }
    }

    /**
     * 获取分类列表
     * @param $codes
     * @return array|BasicCategoryModel[]|\business\company\models\SupplierApplyAdminModel[]|\business\company\models\SupplierDocumentAuditModel[]|\business\company\models\SupplierDocumentModel[]|\business\company\models\SupplierInfoManageCondModel[]|\business\company\models\SupplierModel[]|\business\company\models\SupplierSerAreaModel[]|\business\company\models\SupplierServiceAreaModel[]|\business\company\models\SupplierServiceCategoryModel[]|\business\user\models\BusinessCardModel[]|\business\user\models\UserBusinessScopeModel[]|\yii\db\ActiveRecord[]
     */
    public function getCategoryListByCodes($codes)
    {
        return BasicCategoryModel::find()->select('category_code as code,category_name as name')->where(['in', 'category_code', explode(',', $codes)])
            ->andWhere('category_status=1')->asArray()->all();
    }

    /***
     * 搜索服务分类
     * @param $keywords
     * @return array|bool|\yii\db\ActiveRecord[]
     */
    public function searchCategoryByKeywords($keywords){
        try {
            $result = BasicCategoryModel::find()->select(['category_code', 'category_name'])->where('is_leaf=1 and category_status=1 ')
                ->andFilterWhere(['like', 'category_name', $keywords])->asArray()->all();
            return $result;
        }catch (Exception $e){
            Yii::getLogger()->log('=====BasicCategoryService::searchCategoryByKeywords:'
                . $e->getMessage() . '======', Logger::LEVEL_ERROR);
            return false;
        }
    }
}